package com.ctshk.rpc.hotel.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.hotel.dto.HotelRoomFacilitiesDTO;
import com.ctshk.rpc.hotel.dto.HotelRoomTypeDTO;
import com.ctshk.rpc.hotel.dto.HotelRoomTypeManagerListDTO;
import com.ctshk.rpc.hotel.entity.HotelRoomFacilities;
import com.ctshk.rpc.hotel.entity.HotelRoomType;
import com.ctshk.rpc.hotel.mapper.HotelRoomFacilitiesMapper;
import com.ctshk.rpc.hotel.mapper.HotelRoomTypeMapper;
import com.ctshk.rpc.hotel.req.HotelRoomTypeManagerListReq;
import com.ctshk.rpc.hotel.req.HotelRoomTypeReq;
import com.ctshk.rpc.hotel.service.IHotelRoomTypeService;
import com.ctshk.rpc.system.dto.SysAgentDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 酒店房型 服务实现类
 * </p>
 *
 * @author yinhuan
 * @since 2021-03-03
 */
@DubboService
public class HotelRoomTypeServiceImpl extends ServiceImpl<HotelRoomTypeMapper, HotelRoomType> implements IHotelRoomTypeService {
    @Autowired
    private HotelRoomTypeMapper hotelRoomTypeMapper;
    @Autowired
    private HotelRoomFacilitiesMapper hotelRoomFacilitiesMapper;

    /**
     * 分页查询酒店房型列表-房型表，房型设施表，费用说明暂时没找到。
     * @param req
     * @return
     */
    @Override
    public PageResponse<HotelRoomTypeManagerListDTO> queryList(HotelRoomTypeManagerListReq req) {
        IPage<HotelRoomTypeManagerListDTO> agentPage = new Page<>(req.getPageNo(),req.getPageSize());
        agentPage = hotelRoomTypeMapper.queryList(req,agentPage);
        PageResponse<HotelRoomTypeManagerListDTO> result = new PageResponse<>(agentPage.getRecords(),agentPage.getCurrent() == 1,
                agentPage.getTotal() <= (agentPage.getCurrent() * agentPage.getSize()),
                agentPage.getTotal(), agentPage.getCurrent(), agentPage.getSize());
        return result;
    }

    /**
     * 校验入参
     * @param hotelRoomTypeReq
     * @param user
     * @return
     */
    private Result checkProductReq(HotelRoomTypeReq hotelRoomTypeReq, TokenUser user){
        if(Objects.isNull(user)){
            return Result.failed(SystemError.USER_1000);
        }
        if(Objects.isNull(hotelRoomTypeReq)){
            return Result.failed(SystemError.BUS_PRODUCT_9004);
        }
        return null;
    }

    /**
     * 新增房型信息
     * @param hotelRoomTypeReq
     * @param user
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Result saveHotelRoomType(HotelRoomTypeReq hotelRoomTypeReq, TokenUser user) {

        Result checkResult = checkProductReq(hotelRoomTypeReq,user);
        if(!Objects.isNull(checkResult)){
            return checkResult;
        }
        //保存酒店房型
        HotelRoomType hotelRoomType = EntityUtil.copy(hotelRoomTypeReq, HotelRoomType.class);
        hotelRoomType.setId(SnowflakeIdWorker.nextId());
        hotelRoomType.setGmtCreate(LocalDateTime.now());
        hotelRoomType.setCreateId(user.getId());
        hotelRoomType.setIsDeleted(IsDeletedCode.NO.getCode());
        hotelRoomType.setFacilities(hotelRoomTypeReq.getHotelRoomFacilitiesReq());
        // 默认设置第一张图片为房型封面图
        if (StringUtils.isBlank(hotelRoomTypeReq.getCoverImg()) && !StringUtils.isBlank(hotelRoomTypeReq.getPhotoJson())) {
            JSONArray jsonArray = JSON.parseArray(hotelRoomTypeReq.getPhotoJson());
            JSONObject jsonObject = JSON.parseObject(jsonArray.get(0).toString());
            hotelRoomType.setCoverImg(jsonObject.getString("url"));
        }
        hotelRoomTypeMapper.insert(hotelRoomType);

        //保存酒店房型设施
        /*if(hotelRoomTypeReq.getHotelRoomFacilitiesReq()!=null){
            for (int i = 0; i <hotelRoomTypeReq.getHotelRoomFacilitiesReq().size(); i++) {
                HotelRoomFacilities hotelRoomFacilities = EntityUtil.copy(hotelRoomTypeReq.getHotelRoomFacilitiesReq().get(i), HotelRoomFacilities.class);
                long hotelFacilitiesId = IdWorker.getId();
                hotelRoomFacilities.setId(hotelFacilitiesId);
                hotelRoomFacilities.setHotelId(hotelRoomType.getId());
                hotelRoomFacilities.setCreateId(user.getId());
                hotelRoomFacilities.setGmtCreate(LocalDateTime.now());
                hotelRoomFacilities.setIsDeleted(IsDeletedCode.NO.getCode());
                hotelRoomFacilitiesMapper.insert(hotelRoomFacilities);
            }
        }*/
        return Result.success();
    }

    /**
     * 修改房型信息
     * @param req
     * @param id
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public Result updateHotelRoomType(HotelRoomTypeReq req, Long id) {

        if(id == null){
            return Result.failed(SystemError.USER_1000);
        }
        if(req == null){
            return Result.failed(SystemError.HOTEL_10011);
        }
        //现根据HorelId查出酒店信息
        HotelRoomType hotelRoomType = hotelRoomTypeMapper.selectById(req.getId());
        if(Objects.isNull(hotelRoomType)){
            return Result.failed(SystemError.HOTEL_10010);
        }
        //修改酒店信息
        hotelRoomType = EntityUtil.copy(req,HotelRoomType.class);
        hotelRoomType.setModifiedId(id);
        hotelRoomType.setGmtModified(LocalDateTime.now());
        hotelRoomType.setFacilities(req.getHotelRoomFacilitiesReq());
        // 默认设置第一张图片为房型封面图
        if (StringUtils.isBlank(req.getCoverImg()) && !StringUtils.isBlank(req.getPhotoJson()) && StringUtils.isBlank(hotelRoomType.getCoverImg())) {
            JSONArray jsonArray = JSON.parseArray(req.getPhotoJson());
            JSONObject jsonObject = JSON.parseObject(jsonArray.get(0).toString());
            hotelRoomType.setCoverImg(jsonObject.getString("url"));
        }
        hotelRoomTypeMapper.updateById(hotelRoomType);
        //删除该酒店下所有设施信息
        /*if(CollectionUtils.isNotEmpty(req.getHotelRoomFacilitiesReq())){
            QueryWrapper<HotelRoomFacilities> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(HotelRoomFacilities::getRoomId,hotelRoomType.getId());
            queryWrapper.lambda().eq(HotelRoomFacilities::getIsDeleted, IsDeletedCode.NO.getCode());
            List<HotelRoomFacilities> hotelRoomFacilities = hotelRoomFacilitiesMapper.selectList(queryWrapper);
            for(int i=0;i<hotelRoomFacilities.size();i++){
                hotelRoomFacilitiesMapper.deleteById(hotelRoomFacilities.get(i).getId());
            }
            //添加酒店设施信息
            for (int i = 0; i <req.getHotelRoomFacilitiesReq().size() ; i++) {
                HotelRoomFacilities hotelRoomFacilitiesObj = EntityUtil.copy(req.getHotelRoomFacilitiesReq().get(i), HotelRoomFacilities.class);
                long hotelRoomFacilitiesId = IdWorker.getId();
                hotelRoomFacilitiesObj.setId(hotelRoomFacilitiesId);
                hotelRoomFacilitiesObj.setHotelId(hotelRoomType.getId());
                hotelRoomFacilitiesObj.setCreateId(id);
                hotelRoomFacilitiesObj.setGmtCreate(LocalDateTime.now());
                hotelRoomFacilitiesObj.setIsDeleted(IsDeletedCode.NO.getCode());
                hotelRoomFacilitiesMapper.insert(hotelRoomFacilitiesObj);
            }
        }*/
        return Result.success();
    }

    /**
     * 根据id查询代理商详情
     *
     * @param id 代理商id
     * @return
     */
    @Override
    public Result<HotelRoomTypeDTO> query(Long id) {
        HotelRoomType hotelRoomType = hotelRoomTypeMapper.selectById(id);
        if(null != hotelRoomType){
            HotelRoomTypeDTO hotelRoomTypeDTO = EntityUtil.copy(hotelRoomType, HotelRoomTypeDTO.class);
            return Result.success(hotelRoomTypeDTO);
        }
        return Result.failed(SystemError.SYS_411);
    }
}

